<template>
  <div class="right-container">
    <div class="filter">
      <div class="title">
        {{ currentTab === 1 ? '班级错题' : '学生错题' }}
      </div>
      <div class="correct-rate">
        <div class="text">正确率：</div>
        <div class="rates">
          <el-checkbox-group v-model="checkList" @change="checkedRateList">
            <el-checkbox
              v-for="rate in rates"
              :key="rate.label"
              :value="rate.value"
              :label="rate.label"
            />
          </el-checkbox-group>
        </div>
      </div>
      <div class="question-type" v-if="currentTab === 2">
        <div class="text">题型：</div>
        <div class="type">
          <el-checkbox-group
            v-model="checkedQuestionTypes"
            @change="changeType"
          >
            <el-checkbox-button
              v-for="type in questionTypes"
              :key="type.data.id"
              :value="type"
            >
              {{ type.data.name }}
            </el-checkbox-button>
          </el-checkbox-group>
        </div>
      </div>
    </div>
    <div class="data-list-container" v-loading="isLoading">
      <!-- 顶部导航栏 -->
      <div class="header">
        <div class="left">
          <div class="header-item" @click="sortBy('time')">
            <div>时间</div>
            <div class="icons">
              <el-icon
                :size="10"
                :color="getSortColor('time')"
                :style="{
                  transform:
                    getSortOrder('time') === 'asc'
                      ? 'rotate(0deg)'
                      : 'rotate(180deg)',
                  transition: 'all 0.35s'
                }"
              >
                <IEpCaretTop />
              </el-icon>
            </div>
          </div>
          <div class="header-item" @click="sortBy('accuracy')">
            <div>正确率</div>
            <div class="icons">
              <el-icon
                :size="10"
                :color="getSortColor('accuracy')"
                :style="{
                  transform:
                    getSortOrder('accuracy') === 'asc'
                      ? 'rotate(0deg)'
                      : 'rotate(180deg)',
                  transition: 'all 0.35s'
                }"
              >
                <IEpCaretTop />
              </el-icon>
            </div>
          </div>
        </div>
        <div class="right">
          <div>
            共<span style="color: #5466e7">{{ totalItems }}</span
            >题
          </div>
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="totalItems"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 数据列表 -->
      <el-scrollbar ref="scrollbarRef">
        <template v-if="mistakesQuestion.length !== 0">
          <GeneralityTopic
            @generalityNextPage="debounceGetPersonalizedMistakes"
            :topicData="mistakesQuestion"
          />
        </template>
        <template v-else>
          <el-empty />
        </template>
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup>
import { ref, defineModel, watch, nextTick, computed } from 'vue'

import { computedStageId } from '@/utils'

import { debounce } from 'lodash'

import { storeToRefs } from 'pinia'

import { getQuestionType } from '@/apis/target-boost/index'
import { getTopicList } from '@/apis/knowledge/index'

import { useAuthStore } from '@/stores'

import GeneralityTopic from '@/views/target-boost/target-knowledge-point/components/GeneralityTopic.vue'

const props = defineProps({
  selectTime: Array,
  currentGradeNum: Number,
  classId: String
})

const authStore = useAuthStore()

const { classType } = storeToRefs(authStore)

const checkedStudent = defineModel('checkedStudent')

const currentTab = defineModel('currentTab')

const isLoading = ref(false)

// right-header逻辑
const checkList = ref([
  {
    max: 1,
    min: 0
  }
])
const rates = [
  {
    value: {
      max: 1,
      min: 0
    },
    label: '不限'
  },
  {
    value: {
      max: 0.9,
      min: 0
    },
    label: '≤90%'
  },
  {
    value: {
      max: 0.8,
      min: 0
    },
    label: '≤80%'
  },
  {
    value: {
      max: 0.7,
      min: 0
    },
    label: '≤70%'
  },
  {
    value: {
      max: 0.6,
      min: 0
    },
    label: '≤60%'
  },
  {
    value: {
      max: 0.5,
      min: 0
    },
    label: '≤50%'
  },
  {
    value: {
      max: 0.4,
      min: 0
    },
    label: '≤40%'
  },
  {
    value: {
      max: 0.3,
      min: 0
    },
    label: '≤30%'
  }
]
// 弄成单选
let isEnd_knowledge = false
const checkedRateList = async checkedList => {
  isEnd_knowledge = false
  checkList.value = checkedList
  console.log(checkedList.value)

  checkList.value.shift()
  // 如果没有默认不限
  if (checkList.value.length === 0) {
    checkList.value = [
      {
        max: 1,
        min: 0
      }
    ]
  }
  await debounceGetPersonalizedMistakes()
}
const checkedQuestionTypes = ref([{ data: { id: 0, name: '全部' } }])

const changeType = async value => {
  isEnd_knowledge = false
  if (value.length === 0) {
    checkedQuestionTypes.value = [{ data: { id: 0, name: '全部' } }]
  } else if (value[value.length - 1]?.data?.name !== '全部') {
    // 查找checkedQuestionTypes的'全部'的元素，删除
    checkedQuestionTypes.value = checkedQuestionTypes.value.filter(
      item => item.data.name !== '全部'
    )
  } else {
    checkedQuestionTypes.value = [{ data: { id: 0, name: '全部' } }]
  }
  await debounceGetPersonalizedMistakes()
}

// 获取题型
const questionTypes = ref([])

const getQuestionTypeFn = async () => {
  const params = {
    subject_id: authStore.nowGlobalSubjectId,
    stage_id: computedStageId(props.currentGradeNum)
  }
  const res = await getQuestionType(params)
  if (res.data) {
    questionTypes.value = [{ data: { id: 0, name: '全部' } }, ...res.data]
  } else {
    questionTypes.value = [{ data: { id: 0, name: '全部' } }]
  }
}
// 当
watch(
  () => authStore.nowGlobalSubjectId,
  async () => {
    if (!authStore.nowGlobalSubjectId) return

    await getQuestionTypeFn()
    isEnd_knowledge = false
    // 清空数据
    currentPage.value = 1
    totalItems.value = 0
    mistakesQuestion.value = []
  },
  {
    immediate: true
  }
)

const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const mistakesQuestion = ref([])
const sortCriteria = ref({ key: '', order: '' }) // 用于存储当前的排序字段和顺序

const sortBy = key => {
  if (sortCriteria.value.key === key) {
    if (sortCriteria.value.order === 'asc') {
      sortCriteria.value.order = 'desc'
    } else if (sortCriteria.value.order === 'desc') {
      sortCriteria.value.order = ''
      sortCriteria.value.key = ''
    } else {
      sortCriteria.value.order = 'asc'
    }
  } else {
    sortCriteria.value.key = key
    sortCriteria.value.order = 'asc'
  }
}

// 1：时间（id）；-1：时间逆序；2：正确率；-2：正确率逆序
// watch会监听sortCriteria.value的变化，如果变化了，就执行请求数据方法
const currentSortState = computed(() => {
  const { key, order } = sortCriteria.value
  if (key === 'time' && order === 'asc') return 1
  if (key === 'time' && order === 'desc') return -1
  if (key === 'accuracy' && order === 'asc') return 2
  if (key === 'accuracy' && order === 'desc') return -2

  return 1 // 表示时间排序
})

const getSortColor = key => {
  return sortCriteria.value.key === key ? '#3D54D9' : ''
}

const getSortOrder = key => {
  return sortCriteria.value.key === key ? sortCriteria.value.order : ''
}

let page_size_knowledge = 10

const knowledgePointList = defineModel('knowledgePointList')
watch(
  () => [
    knowledgePointList.value,
    currentSortState.value,
    authStore.nowGlobalSubjectId,
    props.selectTime
  ],
  async () => {
    isEnd_knowledge = false
    await debounceGetPersonalizedMistakes()
  },
  {
    deep: true
  }
)

// 遍历所有类型，拿到id并放到数组中
function getAllIds(data) {
  const ids = []

  function traverse(item) {
    if (item.data && item.data.id) {
      ids.push(item.data.id)
    }
    if (Array.isArray(item.children)) {
      item.children.forEach(traverse)
    }
  }

  // 直接遍历传入的数组
  data.forEach(traverse)

  return ids
}

// 获取错题请求方法
async function getPersonalizedMistakes() {
  isLoading.value = true

  if (isEnd_knowledge) {
    isLoading.value = false
    return
  }
  await nextTick()
  const params = {
    class_id: props.classId || '3288131861430344',
    class_type: Number(classType.value),
    start_time: (props?.selectTime && +props?.selectTime[0]) || 1,
    end_time: (props.selectTime && +props.selectTime[1]) || 9999999999,
    subject_id: authStore.nowGlobalSubjectId,
    score_rate_interval: checkList.value[0],
    order_by: currentSortState.value,
    knowledge_ids: currentTab === 1 ? [] : knowledgePointList.value,
    student_id: currentTab === 2 ? [] : checkedStudent.value,
    category: getAllIds(checkedQuestionTypes.value),
    page: currentPage.value,
    size: page_size_knowledge
  }

  if (
    checkList.value.length === 1 &&
    checkList.value[0].max === 1 &&
    checkList.value[0].min === 0
  ) {
    delete params.score_rate_interval
  }
  const { data, msg } = await getTopicList(params)
  isLoading.value = false
  if (msg == 'OK') {
    if (data.total == 0) {
      isEnd_knowledge = true
      mistakesQuestion.value = []
      totalItems.value = data.total
      return
    }
    totalItems.value = data.total
    mistakesQuestion.value = data.data
    if (data.data?.length < page_size_knowledge) {
      isEnd_knowledge = true
    }
  }
}

const debounceGetPersonalizedMistakes = debounce(getPersonalizedMistakes, 500)

watch(
  () => checkedStudent.value,
  async () => {
    isEnd_knowledge = false
    isLoading.value = true
    mistakesQuestion.value = []
    await debounceGetPersonalizedMistakes()
  },
  {
    deep: true
  }
)

// 下一页滚动到顶部
const scrollbarRef = ref(null)
const handlePageChange = async newPage => {
  isEnd_knowledge = false
  currentPage.value = newPage
  await debounceGetPersonalizedMistakes()
  nextTick(() => {
    scrollbarRef.value.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  })
}
</script>
<style lang="less" scoped>
.right-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 21px;

  .filter {
    width: 100%;
    background-color: #fff;
    border-radius: 14px;

    .title {
      font-weight: 700;
      font-size: 18px;
      padding: 17px;
    }

    .text {
      font-weight: 700;
      color: #333;
    }

    .correct-rate {
      display: flex;
      align-items: center;
      height: 50px;
      line-height: 50px;
      margin-left: 20px;
      font-size: 16px;
    }

    .question-type {
      display: flex;
      padding: 10px 20px;
      align-items: center;
      line-height: 50px;

      .text {
        width: 50px;
      }

      .type {
        width: 100%;
        :deep(.el-checkbox-group) {
          display: flex;
          gap: 15px;
          flex-wrap: wrap;

          .el-checkbox-button__inner {
            border: none;

            &:hover {
              color: @theme-color;
              background-color: @gray-background-color;
              border-radius: 4px;
            }
          }

          .is-checked {
            .el-checkbox-button__inner {
              color: @theme-color;
              background-color: @gray-background-color;
              border-radius: 4px;
            }
          }
        }
      }
    }
  }

  .data-list-container {
    flex: 1;
    padding: 20px;
    border-radius: 14px;
    background-color: #fff;
    overflow: hidden;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left {
      display: flex;
      gap: 20px;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .header-item {
    cursor: pointer;
    display: flex;
    align-items: center;

    .icons {
      display: flex;
      flex-direction: column;
    }
  }

  .header-item .el-icon {
    margin-left: 5px;
  }

  .box-card {
    margin-bottom: 20px;
  }

  .number {
    margin-right: 10px;
  }

  .time {
    float: right;
  }
}
</style>
